package com.ruoyi.schoolApp.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.core.domain.R;


import com.ruoyi.schoolApp.domain.WxLoginDo;
import com.ruoyi.schoolApp.mapper.WechatUserMapper;
import com.ruoyi.schoolApp.service.WxLoginService;
import com.sun.xml.internal.bind.v2.TODO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;

/**
 * @author ctl
 * @date 2024-03-11
 */
@Service
@Slf4j
public class WxLoginServiceImpl implements WxLoginService {
    @Value("${wx.minApp.appId}")
    private String appId;

    @Value("${wx.minApp.appSecret}")
    private String appSecret;

    @Value("${wx.minApp.url}")
    private String url;

    @Value("${wx.minApp.grant_type}")
    private String grantType;

    @Resource
    private WechatUserMapper  wechatUserMapper;


/**
 * 获取微信小程序openid
 * @param code code
 * @return 结果
 */
    @Override
    public String getOpenId(String code) {
        if(code ==null ||code.length() ==0){
            return null;
        }
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type={3}";
        String replaceUrl = url.replace("{0}", appId).replace("{1}", appSecret).replace("{2}", code).replace("{3}",grantType);
        log.info("replaceUrl======>{} ",replaceUrl);
        String res = null;
        //请求微信api获取openid
        try {
            res = HttpUtil.get(replaceUrl);
        } catch (Exception e) {
            log.error("获取微信小程序openid失败!");
            e.printStackTrace();
        }

        WxLoginDo wxLoginDo = null;
        //如果res不为空，将json数据转成对象
        if(res != null){
             wxLoginDo = JSONUtil.toBean(res, WxLoginDo.class);
        }
        //转成对象后判断是否存在有错误编码
        if(wxLoginDo != null && StringUtil.isEmpty(wxLoginDo.getErrcode())){
            //检查数据库是否存在该openid对应的用户，若有直接返回token，若没有，创建用户后再生成token
        }


        //todo 完善将openid写入数据库
        return res;
    }


    /**
     * 获取微信小程序的基本信息
     * @param code uni.login传递的code
     * @return 返回session_key 和 openid 等信息
     * @throws JsonProcessingException
     */
    public static Map<String, Object> getWechatBaseInfo(String code) throws JsonProcessingException {
        // 调用微信认证接口，获取 session_key 和 openid 等信息
      return null;
    }

}
